import React, { PureComponent,Fragment } from "react";
import { connect } from "dva";
import router from 'umi/router';
import { Row, Col, Card, Icon, Button, message, Divider, Form, Input, Popconfirm, Badge, Table} from "antd";
import Authorized from '../../../utils/Authorized';
import styles from '../../Pbulic.less';
const FormItem = Form.Item;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');



function fn(data, pid) {
  let result = [], temp;
  if(data && pid) {
    for (let i in data) {
      if (data[i].parentId == pid) {
        result.push(data[i]);
        temp = fn(data, data[i].deptId);
        if (temp.length > 0) {
          data[i].children = temp;
        }
      }
    }
  }
  return result;
}

Array.prototype.ToTreeJson = function (pid) {
  let result = [], temp;
  for (let i in this) {
    if (this[i].parentId == pid) {
      result.push(this[i]);
      temp = fn(this, this[i].deptId);
      if (temp.length > 0) {
        this[i].children = temp;
      }
    }
  }
  return result;
}

const treeData = data =>{
  return data.map(item=>{
    if(item.children){
      return {children:treeData(item.children),key:`${item.deptId}`, name:item.deptName};
    }else{
      return {key:`${item.deptId}`, name:item.deptName};
    }
  })
}



@connect(({ department,loading }) => ({
  resdata: department.resdata,
  loading: department.loading,
  // loading: loading.models.equipment_integrated,
}))
@Form.create()
export default class ListTable extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      currentPage: 1,
      pageSize: 10,
      formValues: {},
      selectedRows:[]
    };
  }

  componentWillUnmount() {

  }


  componentDidMount() {
    const { pageSize } = this.state;
    const { location, dispatch} = this.props;
    const pagesquery = location.query;

    // 列表
    this.getDataList(pagesquery,pageSize,1);


  }


  getDataList(params,pageSize,currentPage) {
    const { dispatch, match } = this.props;
    dispatch({
      type: 'department/fetch_department_list',
      payload: {
        // pageSize,
        // currentPage,
        // ...pagesquery,
        ...params,
      },
    });
  }

  // 批量删除
  handleListDel = (id) => {
    const { dispatch } = this.props;
    const { selectedRows,formValues, pageSize, currentPage } = this.state;
    // if(!id && !selectedRows) return;
    // const deptIds= id ? [id] : selectedRows;

    id && dispatch({
      type: 'department/action_department_del',
      payload: {
        deptIds: [id],
      },
    }).then(()=>{
      message.success("所选部门已删除")
    }).then(()=>{
      this.getDataList(formValues,pageSize,currentPage);
    });


  };

  // 链接跳转-------------------
  handleLink = (action,detailInfoId) =>{
    const { dispatch, match } = this.props;
    // const { formValues, currentPage} = this.state;
    let linkpath;
    switch (action) {
      case 'add':
        linkpath = `/system/department/detail/add`;
        break;
      case 'edit':
        linkpath = `/system/department/${detailInfoId}/edit`;
        break;
      default:
        break;
    }
    router.push({ pathname:`${linkpath}` });
  }


  render() {

    const { resdata, loading } = this.props;
    const { selectedRows } = this.state;


    const columns = [
      {
        title: "部门ID",
        dataIndex: "deptId",
      },
      {
        title: "部门名称",
        dataIndex: "deptName",
      },
      {
        title: "上级部门",
        dataIndex: "parentName",
        render: text => text ? text : "--"
      },
      {
        title: "排序号",
        dataIndex: "sort",
        // sorter: (a, b) => a.sort - b.sort,
        // sortOrder: 'ascend',
      },
      {
        title: "操作",
        dataIndex: "Action",
        width: "15%",
        render: (text, row) => (
            <span>
              <Authorized authority={'10383'} >
                <a onClick={() => this.handleLink('edit',row.deptId)}>修改</a>
                <Divider type="vertical" />
              </Authorized>
              <Authorized authority={'10384'} >
                <Popconfirm title="是否确定要删除?" onConfirm={() => this.handleListDel(row.deptId)}  okText="是" cancelText="否">
                  <a >删除</a>
                </Popconfirm>
              </Authorized>
            </span>
        )
      }
    ];


    return (
      <Card bordered={false}>
          <div className={`${styles.tableList}`}>

            <div className={styles.tableListOperator}>
              <Authorized authority={'10382'} >
                <Button icon="plus" type="primary"  onClick={() => this.handleLink('add',null)}>
                  新增部门
                </Button>
              </Authorized>


            </div>

            <Table
              loading={loading.reslist}
              rowKey="deptId"
              dataSource={resdata.list.ToTreeJson(0)}
              columns={columns}
              onChange={this.handleStandardTableChange}
              pagination={false}
            />

          </div>
      </Card>

    );
  }
}
